const Util = require('../../utils/util.js');
var Data = require("../../utils/data.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    info:'',
    agree:false,
    live_num:1,
    addr_list:'',
    addr_num:0,
    order_price:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this;
    if (e.goods_id) {
      wx.getStorage({
        key: 'token',
        success: function (res) {
          that.setData({
            goods_id: e.goods_id,
            startDate: e.startDate,
            endDate: e.endDate,
            token:res.data
          })
          that.getDate();
          that.orderPrice();
          that.getAddrInfo();
          that.goodsDetail();
        }
      });
    }
  },
  orderPrice:function(){
    var that = this;
    var startDate = that.data.startDate;
    var endDate = that.data.endDate;
    var token = that.data.token;
    var goods_id = that.data.goods_id;
    Util.getOrderPrice({
      token:token,
      goods_id: goods_id,
      start_date: startDate,
      end_date: endDate
    },function(re){
      if(re.code==200){
        that.setData({
          order_price:re.data
        })
      }else{
        that.bindViewTap();
      }
    })
  },
  getAddrInfo:function(){
    var that = this;
    var token = that.data.token;
    Util.getAddrInfo({
      token: token
    }, function (re) {
      if (re.code == 200) {
        var json = new Array();
        json[0] = re.data;
        that.setData({
          addr_list: json,
          addr_num:json.length
        })
      }
    })
  },
  //事件处理函数
  bindViewTap: function () {
    var that = this;
    var startDate = that.data.date;
    var endDate = that.data.tomorrow;
    var goods_id = that.data.goods_id;
    wx.navigateTo({
      url: '../calender/index?pay=1&goods_id='+goods_id+'&&startDate=' + startDate + "&endDate=" + endDate
    })
  },
  getDate: function () {
    var startDate = this.data.startDate;
    var endDate = this.data.endDate;
    var s = startDate.split('-');
    var startD = s[1] +'月'+ s[2]+'日';
    var e = endDate.split('-');
    var endD = e[1] + '月' + e[2] + '日';

    this.setData({
      date: startDate,
      tomorrow: endDate,
      startD: startD,
      endD: endD,
      countD: this.datedifference(startDate, endDate),
      startName: this.checkDay(startDate),
      endName: this.checkDay(endDate)
    });
  },
  goodsDetail: function () {
    var that = this;
    var goods_id = that.data.goods_id;
    Util.getGoodsDetail({
      goods_id: goods_id
    }, function (ret) {
      console.info(ret);
      that.setData({
        info: ret.data
      })
    })
  },
  checkDay: function (str) {
    var date = Data.formatDate(new Date(), "yyyy-MM-dd");
    if (date == str) {
      return '今天';
    }
    var tomorrow1 = new Date();
    tomorrow1.setDate((new Date()).getDate() + 1);
    var tomorrow = Data.formatDate(new Date(tomorrow1), "yyyy-MM-dd");
    if (tomorrow == str) {
      return '明天';
    }
    var weekDay = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    var myDate = new Date(Date.parse(str));
    return weekDay[myDate.getDay()];
  },
  datedifference: function (sDate1, sDate2) {    //sDate1和sDate2是2006-12-18格式  
    var dateSpan,
      tempDate,
      iDays;
    sDate1 = Date.parse(sDate1);
    sDate2 = Date.parse(sDate2);
    dateSpan = sDate2 - sDate1;
    dateSpan = Math.abs(dateSpan);
    iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
    return iDays
  },
  goPay:function(){
    var that = this;
    var token = that.data.token;
    var goods_id = that.data.goods_id;
    var startDate = that.data.date;
    var endDate = that.data.tomorrow;
    var agree = that.data.agree;
    var addr_list = that.data.addr_list;
    var live_num = that.data.live_num;
    var countD = that.data.countD;
    if (addr_list.length != live_num){
      Util.showToast('请添加与入住人数一致的入住人');
      return;
    }else{
      var addr_id = '';
      var n = addr_list.length;
      for (var i = 0; i < n;i++){
        addr_id += addr_list[i].id+',';
      }
    }
    if (!agree){
      Util.showToast('请阅读相关规则并同意');
      return;
    }
    Util.setOrder({
      token: token,
      goods_id: goods_id,
      start_date: startDate,
      end_date: endDate,
      addr_id: addr_id,
      goods_number: countD
    },function(ret){
      if(ret.status==1){
        var wechatData = ret.data;
        wx.requestPayment({
          'appId': wechatData.appId,
          'timeStamp': wechatData.timeStamp,
          'nonceStr': wechatData.nonceStr,
          'package': wechatData.package,
          'signType': 'MD5',
          'paySign': wechatData.paySign,
          success: function (rr) {
            Util.showMsgDialog('支付成功', function () {
              wx.reLaunch({
                url: '/pages/user/order'
              });
            });
          },
          'fail': function (rr) {
            if (rr.errMsg == 'requestPayment:fail cancel' || rr.errMsg == 'requestPayment:fail') {
              Util.showMsgDialog('用户取消支付', function () {
                wx.navigateBack({
                  delta: 2
                });
              });
            }
          }
        });
      }
    })
  },
  addCart:function(e){
    var that = this;
    var live_num = parseInt(that.data.live_num);
    var info = that.data.info;
    var tid = e.currentTarget.dataset.tid;
    if (tid == 1) {
      if (live_num>1){
        live_num--;
      }
    } else {
      if (parseInt(info.live_num) > live_num){
        live_num = live_num+1;
      }else{
        Util.showToast('最多入住' + live_num + '人');
      }
    }
    that.setData({
      live_num: live_num
    });
  },
  radioChange: function (e) {
    var that = this;
    that.setData({
      agree: true
    })
  },
  delAddr:function(e){
    var that = this;
    var id = e.currentTarget.dataset.id;
    var addr_list = that.data.addr_list;
    var num = addr_list.length;
    if (num>1){
      var n = 0;
      var arr = new Array();
      for(var i =0;i<num;i++){
        if(i!=id){
          arr[n] = addr_list[i];
          n++;
        }
      }
      var addr_num = n;
      console.info(addr_num);
      addr_list = arr;
    }else{
      addr_list = [];
      var addr_num = 0;
    }
    that.setData({
      addr_list: addr_list,
      addr_num: addr_num
    })
  },
  checkAddr:function(e){
    wx.navigateTo({
      url: '/pages/user/addr?type_id=1'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})